package com.sgq.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sgq.entity.Permission;
import com.sgq.service.PermissionService;
import com.sgq.utils.Result;
import com.sgq.vo.PermissionQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sgq
 * @since 2024-09-13
 */
@RestController
@RequestMapping("/api/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/{id}")
    public Result getPermissionById(@PathVariable("id") Long id){
        return Result.ok(permissionService.getById(id));
    }

    @GetMapping("/list")
    public Result list(PermissionQueryVo permissionQueryVo){
        List<Permission> list = permissionService.findPermissionList(permissionQueryVo);
        return Result.ok(list);
    }

    @GetMapping("/page")
    public Result page(PermissionQueryVo permissionQueryVo){
        IPage<Permission> page = permissionService.findPage(permissionQueryVo);
        return Result.ok(page);
    }

    /**
     * 查询上级菜单列表
     * @return
     */
    @GetMapping("/parent/list")
    public Result getParentList(){
        //查询上级菜单列表
        List<Permission> permissionList = permissionService.findParentPermissionList();
        //返回数据
        return Result.ok(permissionList);
    }

    @PostMapping("/save")
    public Result save(@RequestBody Permission permission){
        boolean b = permissionService.checkPermissionCode(permission);
        if (b){
            return Result.exist().message("该权限标识已存在");
        }
        return Result.ok(permissionService.save(permission));
    }

    @PutMapping("/update")
    public Result update(@RequestBody Permission permission){
        boolean b = permissionService.checkPermissionCode(permission);
        if (b){
            return Result.exist().message("该权限标识已存在");
        }
        return Result.ok(permissionService.updateById(permission));
    }


    /**
     * 删除方法需调用
     * @param id
     * @return
     */
    @GetMapping("/check/{id}")
    public Result check(@PathVariable("id") Long id){
        //判断菜单是否有子菜单,
        if(permissionService.hasChildrenInPermission(id)){
            return Result.exist().message("该菜单下有子菜单，无法删除");
        }
        //是否被分配角色
        if (permissionService.checkPermissionUsed(id)){
            return Result.exist().message("该菜单已被分配角色，无法删除");
        }
        return Result.ok();
    }

    @DeleteMapping("/delete/{id}")
    public Result update(@PathVariable("id") Long id){
        return Result.ok(permissionService.removeById(id));
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody Long [] ids){
        return Result.ok(permissionService.removeBatchByIds(Arrays.asList(ids)));
    }

}

